/* eslint-disable @typescript-eslint/ban-ts-comment */
import { defineComponent, h, inject, PropType, provide, reactive, ref, nextTick, watch, computed, getCurrentInstance } from 'vue';

import { useDialog } from '@hooks/useDialog';
/* model */
import { ActionCreateParams, ConnectorField, ConnectorFromField, ConnectorModuleComponentNameEnum, ConnectorOptionsFieldOption, ConnectorToField } from '@src/modules/connector/model'
import { DataType } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/model/enum/data';
/* components */
import FormConnectorDataRuleSettingDataSource, { FieldUpdateResult } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/components/FormConnectorDataRuleSettingDataSource'
import { ConnectorModuleConnectorDialogDetailActionCreate } from '@src/modules/connector/components'
import ConnectorModuleRuleFormItem from '@src/modules/connector/components/rule-form/item'
import { ConnectorRuleFormItemType } from '@src/modules/connector/types'
/* style */
import '@src/modules/connector/components/rule-form/item-form-app.scss'

import { t } from '@src/locales';
import { uuid } from '@src/util/lang/string';
import { triggerFormSettingInterfaceList } from '@src/api/ConnectorApi';
import { covertSetForDataKey } from '@src/modules/connector/util/convert';
import { createConnectorRuleFormItem, convertTriggerAppFormFieldValue } from '@src/modules/connector/util'
import { cloneDeep, isString } from 'lodash';
import { message } from '@src/util/message';

const baseCreateActionParams = {
  apiId: '',
  toBizTypeName: '',
  toRequestFieldList: [],
  toResponseFieldList: [],
  request: [createConnectorRuleFormItem()],
  relationAppForm: [],
  response: {
    enName: '',
    cnName: ''
  }
}


export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleRuleFormItemApp,
  props: {
    fromFieldList: {
      type: Array as PropType<ConnectorFromField[]>,
      default: () => ([])
    },
    fromBizTypeName: {
      type: String as PropType<string>,
      default: ''
    },
    value: {
      type: [String, Object] as PropType<string | Record<string, any>>,
      default: ''  
    },
    isDisabledFromFieldSelect: {
      type: Boolean as PropType<boolean>,
      default: ()=> false
    },
    currentToField: {
      type: Object as PropType<ConnectorToField | undefined>,
      default: ()=> undefined
    },
    parentFieldName: {
      type: String as PropType<string>,
      default: ''  
    },
    parentValue: {
      type: Object as PropType<ConnectorRuleFormItemType | undefined>,
      default: ()=> undefined
    },
    clearable: {
      type: Boolean as PropType<boolean>,
      default: ()=> false
    },
    // 来自其余页面的页面类型
    fromPageType: {
      type: String as PropType<string>,
      default: () => ''
    }
  },
  emits: ['change'],
  setup(props, { emit }) {
    // eslint-disable-next-line vue/no-setup-props-destructure
    const { isDisabledFromFieldSelect, parentFieldName, parentValue } = props
    const fromFieldList = computed(()=> props.fromFieldList)
    const currentToField = computed(()=> props.currentToField)
    const fromBizTypeName = computed(()=> props.fromBizTypeName)
    const value = computed(()=> props.value)
    // @ts-ignore
    const { proxy } = getCurrentInstance()

    const isConfirm = ref(false)
    const modalCompKey = ref(uuid())

    const { visible, showDialog, hideDialog } = useDialog()

    const actionCreateParams = ref<ActionCreateParams>(cloneDeep(baseCreateActionParams))

    const selectField = ref({
      cnName: '',
      enName: ''
    })

    const appFromItem = ref(null)
    const formBuildComponent = ref(null)

    const textValue = computed(()=> {
      if(!isConfirm.value && props.value.length === 0) return '-' 
      const jsonParsedValue = isString(props.value) ? JSON.parse(props.value) : props.value
      const { toBizTypeName = '', response = { cnName: '', enName: ''}} = jsonParsedValue
      return `${toBizTypeName}-${response.cnName || ''}` || ''
    })

    const getAttributes = () => {
      return {
        class: ConnectorModuleComponentNameEnum.ConnectorModuleRuleFormItemAppDialog,
        props: {
          title: t('common.connector.getOtherFormValue'),
          show: visible.value,
          appendToBody: true
        },
        on: {
          'update:show': (v: boolean) => {
            v ? showDialog() : hideDialog()
          }
        }
      }
    }

    const generateSelectFieldInstance = ()=> {
      const mockRenderInstance = {
        currentToField: currentToField.value,
        parentFieldName,
        value: {
          rightFieldValue: actionCreateParams.value?.response.enName || ''
        },
        fromFieldList: actionCreateParams.value.toResponseFieldList || [],
        rightFieldSelectKey: uuid(),
        isTrigger: false,
        parentValue,
        isDisabledFromFieldSelect,
        // @ts-ignore
        filterTypeTree: ConnectorModuleRuleFormItem.methods.filterTypeTree,
        // @ts-ignore
        rightFieldList: [],
        // @ts-ignore
        renderRightFromFieldFormFieldSelect: ConnectorModuleRuleFormItem.methods.renderRightFromFieldFormFieldSelect,
        onRightFromFieldFromFieldSelectChangeHandler: (v: any)=> {

          selectField.value.enName = v
          nextTick(()=> {
            const rightFromFieldFormFieldSelectRefInc = proxy.$refs?.rightFromFieldFormFieldSelectRef
            rightFromFieldFormFieldSelectRefInc.$nextTick(()=> {
              selectField.value.cnName = rightFromFieldFormFieldSelectRefInc?.inputValue || rightFromFieldFormFieldSelectRefInc?.presentText || ''
            })
          })

          // 强制隐藏
          const popperEls = document.querySelectorAll('.connector-module-rule-form-item-right-from-field-form-field-select__popper')
          Array.prototype.forEach.call(popperEls, (el)=> {
            el.style.display = 'none'
          })
   
        },
      }
      

      // @ts-ignore
      mockRenderInstance.rightFieldList = ConnectorModuleRuleFormItem.computed.rightFieldList.call(mockRenderInstance)

      return mockRenderInstance

    }
    const fetchInterfaceDetail = async (apiId: string, request: ConnectorOptionsFieldOption[] | ConnectorRuleFormItemType[] = [])=> {
      try {
        const { data = {}, success = false, message: msg = '' } = await triggerFormSettingInterfaceList({ apiId } )

        if(success) {
  
          const covertResultData = () => {
            const { toRequestFieldList: convertRequestFieldList = [], toResponseFieldList: convertResponseFieldList = [] } = covertSetForDataKey(data, ['toRequestFieldList', 'toResponseFieldList'], ['supportInsert'])
            const needConvert = request.length > 0 && !request.some((item: any) => item?.componentName)
      
            // @ts-ignore
            const { request: convertRequest } = needConvert ? JSON.parse(convertTriggerAppFormFieldValue(props.value, false, true, convertRequestFieldList)) : { request: [] }
            return {
              toRequestFieldList: convertRequestFieldList,
              toResponseFieldList: convertResponseFieldList,
              request: needConvert ? convertRequest : request
            }
          }
    
          actionCreateParams.value = { ...actionCreateParams.value, ...covertResultData() }
        } else {
          message.error(msg)
        }
      } catch(e) {
        console.error('[fetchInterfaceDetail error]', e)
      }
    }

    const handleUpdate = (params: FieldUpdateResult, request = [])=> {
      resetSelectField()
      if(params.newValue.length > 0) {
        const { toRequestFieldList = [], toResponseFieldList = [], label:toBizTypeName = '' } = params.selectItem
        const apiId = params.selectItem.value
        const newParams = {
          apiId,
          toBizTypeName,
          toRequestFieldList,
          toResponseFieldList,
          request: [],
          relationAppForm: actionCreateParams.value.relationAppForm,
          response: {}
        }
        actionCreateParams.value = newParams
        fetchInterfaceDetail(apiId, request)
      } else {
        restCreateActionParams()
      }
      actionCreateParams.value.relationAppForm = params.newValue
    }

    const resetSelectField = ()=> {
      selectField.value = {
        cnName: '',
        enName: ''
      }
    }



    const onConnectorInsertRuleFormInputHandler = (v: ConnectorRuleFormItemType[]) => {
      actionCreateParams.value.request = v
    }

    const restCreateActionParams = ()=> {
      actionCreateParams.value = cloneDeep(baseCreateActionParams)
    }

    /**
     * Description 关闭对应的弹窗事件
     * @returns {any}
     */
    const handleCloseModal = (restValue = true): void => {
      // restValue && restCreateActionParams()
      hideDialog()
      if(!isConfirm.value) restCreateActionParams()
    }

    const handleSubmit = async ()=> {
      // @ts-ignore
      const validated = await formBuildComponent.value.validate()

      if(validated) {
        actionCreateParams.value.response = cloneDeep(selectField.value)
        emit('change', actionCreateParams.value)
        isConfirm.value = true
        hideDialog()
      } 

    }

    const handleShowDialog = async ()=> {
      convertDefaultValue(value.value)
      showDialog()
    }

    const convertDefaultValue = (n: string)=> {
      try {
        const jsonParsedValue = n && isString(n) ? JSON.parse(n) : {}
        const { relationAppForm, toBizTypeName = '', response = { cnName: '', enName: ''}, apiId = '', request = []} = jsonParsedValue
    
        if(apiId) {
          handleUpdate({
            field: {fieldName: ''},
            newValue: relationAppForm,
            oldValue: null,
            selectItem: {
              value: apiId,
              label: toBizTypeName
            }
          }, request)
        }
        const clonedResponse = cloneDeep(response)
        selectField.value = response
        actionCreateParams.value.response = clonedResponse
      } catch(e) {
        console.log('convertDefaultValue', e)
      }
    }

    const handleClear = (event) => {
      event.stopPropagation();
      // 重置 actionCreateParams
      actionCreateParams.value = cloneDeep(baseCreateActionParams);
      // 清空 selectField
      selectField.value = {
        cnName: '',
        enName: ''
      };
      // 重置 isConfirm 状态
      isConfirm.value = false;
      // 触发 change 事件，通知父组件值已被清空
      emit('change', {});
    }    

    provide('isTrigger', false)


    return () => {
      const { toRequestFieldList, toBizTypeName, request, relationAppForm = [] } = actionCreateParams.value
      return (
        <div class="connector-module-rule-form-item-app-box"> 
          <div class="connector-module-rule-form-item-app-form-field" onClick={handleShowDialog}>
            { textValue.value !== '-' ? <span class="text">{ textValue.value}</span> : <span class="placeholder">请选择</span>}
            { textValue.value !== '-' && props?.clearable && <i class="el-icon-circle-close" onClick={handleClear}></i> }
          </div>
          <base-modal {...getAttributes()} key={modalCompKey.value}>
            <div class="connector-module-rule-form-item-app-dialog__content"> 
              <form-builder value={actionCreateParams.value} ref={formBuildComponent}>
                <form-item label={t('common.connector.associatedForm')} required ref={appFromItem}>
                  {visible.value 
                    ? <FormConnectorDataRuleSettingDataSource 
                      value={relationAppForm}
                      type={DataType.Trigger}
                      fromPageType={props.fromPageType}
                      onInput={(params: FieldUpdateResult) => handleUpdate(params)}/> 
                    : null
                  }
                </form-item>
                <form-item label={t('common.connector.filterData')}>
                  <ConnectorModuleConnectorDialogDetailActionCreate
                    showDetailType={false}
                    showTitle={false} 
                    value={request}
                    // @ts-ignore
                    fromFieldList={fromFieldList.value}
                    fromBizTypeName={fromBizTypeName.value}
                    // @ts-ignore
                    toFieldList={toRequestFieldList}
                    toBizTypeName={toBizTypeName}
                    onInput={onConnectorInsertRuleFormInputHandler} />
                </form-item>
                <form-item label={t('common.connector.chooseFieldData')}>
                  {generateSelectFieldInstance().renderRightFromFieldFormFieldSelect(h)}
                </form-item>
              </form-builder>
            </div>
            <div class="footer" slot="footer">
              <el-button onClick={handleCloseModal}> {t('common.base.cancel')} </el-button>
              <el-button type="primary" onClick={handleSubmit}>{t('common.base.save')}</el-button>
            </div>
          </base-modal> 
        </div>
      )
    }
  
  }
})